package com.zzy.demo.config;

import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 数据拦截器
 * @author guokaige
 *
 */
public class DataInterceptor implements HandlerInterceptor {
	
	
	private static final String REDIRECT_API="redirect";
	
	private static final String ERROR_API="error";
	
	private static final String LOGIN_API="login";
	
	private Logger log=LoggerFactory.getLogger(this.getClass());
	
	
	
	
	

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		//session拦截
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		// 验证请求是否
		String requestUrl = request.getRequestURI();
		
		log.debug("请求的api---------------"+requestUrl);
		
		if(checkCurrentURL(requestUrl)){
			Object  user = request.getSession().getAttribute("user");
			if(user != null) {  
				//返回true，则这个方面调用后会接着调用postHandle(),  afterCompletion()
				return true;  
			}else{
				// 未登录
				PrintWriter out = response.getWriter();
				StringBuilder builder = new StringBuilder();
				builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
				builder.append("alert(\"页面过期，请重新登录\");");
				builder.append("window.top.location.href=\"");
				builder.append(request.getContextPath());
				builder.append("/login\";</script>");
				out.print(builder.toString());
				out.close();
				return false;
			} 
		}else{
			return true;
		}
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
		
		if (null !=modelAndView&& null!=modelAndView.getViewName()){
			
     		String viewName = modelAndView.getViewName().toUpperCase();
			if(!viewName.startsWith(DataInterceptor.REDIRECT_API.toUpperCase())){
				//得到当前action的请求路径  
				Map<String,Object> model=modelAndView.getModelMap();
				model.put("base", request.getContextPath());
				
				//url地址
				 String basePathUrl = request.getScheme() + "://"
				               + request.getServerName() + ":"
							   + request.getServerPort()
							   + request.getContextPath() + "/";
				request.setAttribute("basePathUrl", basePathUrl);
			}
		}
		//System.out.println(">>>DataInterceptor>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		//System.out.println(">>>DataInterceptor>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
	}

	
	
	private boolean checkCurrentURL(String requestUrl){
		if(requestUrl.indexOf(DataInterceptor.ERROR_API)>0  || requestUrl.indexOf(DataInterceptor.LOGIN_API)>0 ){
			return false;
		}
		//return true;
		//默认不拦截
		return false;  
	}
	
	
}